<?php

namespace app\admin\controller;

use app\admin\model\userModel;
use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;
use think\Db;

/**
 * 后台入口
 * Class Index
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 10:41
 */
class Index extends BasicAdmin
{
    public function __construct(App $app = null)
    {
        $this->usermodel  =new userModel();
        parent::__construct($app);
    }

    /**
     * 后台框架布局
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        NodeService::applyAuthNode();
        $list = (array)Db::name('adminMenu')->where(['status' => '1'])->order('sort asc,id asc')->select();

        $menus = $this->buildMenuData(ToolsService::arr2tree($list), NodeService::get(), !!session('user'));

        if (empty($menus) && !session('user.id')) {
            $this->redirect('@admin/login');
        }
        return $this->fetch('', ['title' => '系统管理', 'menus' => $menus]);
    }

    /**
     * 后台主菜单权限过滤
     * @param array $menus 当前菜单列表
     * @param array $nodes 系统权限节点数据
     * @param bool $isLogin 是否已经登录
     * @return array
     */
    private function buildMenuData($menus, $nodes, $isLogin)
    {
        foreach ($menus as $key => &$menu) {
            !empty($menu['sub']) && $menu['sub'] = $this->buildMenuData($menu['sub'], $nodes, $isLogin);
            if (!empty($menu['sub'])) {
                $menu['url'] = '#';
            } elseif (preg_match('/^https?\:/i', $menu['url'])) {
                continue;
            } elseif ($menu['url'] !== '#') {
                $node = join('/', array_slice(explode('/', preg_replace('/[\W]/', '/', $menu['url'])), 0, 3));
                $menu['url'] = url($menu['url']) . (empty($menu['params']) ? '' : "?{$menu['params']}");
                if (isset($nodes[$node]) && $nodes[$node]['is_login'] && empty($isLogin)) {
                    unset($menus[$key]);
                } elseif (isset($nodes[$node]) && $nodes[$node]['is_auth'] && $isLogin && !auth($node)) {
                    unset($menus[$key]);
                }
            } else {
                unset($menus[$key]);
            }
        }

        return $menus;
    }

    /**
     * 主机信息显示
     * @return string
     */
    public function main()
    {
        //会员类型对比 角色
        $data['getper'] = self::getper(1);
       //交易金额
        $data['money'] = self::detMoney();
        //提现金额
        $data['withdrawa']= self::withdrawa();
        //溢出资金
        $data['overflow'] = self::overflow();
        //满额用户
        $data['capital'] = self::usercapital();

        return $this->fetch('', ['title'=> '后台首页','data'=>$data]);
    }

    /**
     * 满额用户
     */
    public function usercapital(){

        $list = Db::name('capital')->alias('a')
            ->join('t_user b','a.uid=b.id','left')
           ->join('t_user_role c','b.role_id=c.id','LEFT')
           ->where(['a.status'=>1,'a.type'=>2])
           ->field('a.consumer,a.updated_at,c.max_pay')
           ->select();
       $config = Db::name('config')->select();

       $role = Db::name('user_role')->where(['status'=>1])->select();
        $data['maxPay'] = 0;
        $where = date('Y-m-d');
        $data['todayMaxPay'] = 0;

        foreach ($list as $v){
            if($v['consumer']>$v['max_pay']){
                $data['maxPay']++;//历史满额消费人数
                if($where < $v['updated_at']){
                    $data['todayMaxPay']++;
                }
            }
        }

        return $data;

    }

    /**
     * 溢出记录
     */

    public function overflow(){
        $list = Db::name('overflow_log')->field('money,addtime,type')->select();

        $money = 0;
        $data['money'] = 0;
        $data['num'] = 0;

        $data['moneytoday'] = 0;
        $data['todaynum'] = 0;
        $where = strtotime(date('Y-m-d'));

        foreach ($list as $v){
            if($v['addtime'] > $where){
                $data['moneytoday'] += $v['money'];
                $data['todaynum'] ++;
            }
            $data['num'] ++;
            $data['money'] += $v['money'];
        }
        return $data;
    }

    /**
     * 提现金额
     */
    public function withdrawa(){
        $data = Db::name('withdraw')->where(['usertype'=>'1,2,3,5','status'=>2])->field('money,addtime')->select();
        $code['count'] = count($data);
        $where = strtotime(date('Y-m-d'));
        $code['newnum'] = 0;
        $code['money'] = 0;
        $code['newMoney'] =0;
        foreach($data as $val){
            $code['money'] += $val['money'];
            if($val['addtime'] > $where){
                $code['newMoney'] +=$val['money'];
                $code['newnum']++;
            }
        }
        return $code;
    }

    /**
     * @return array
     * 消费金额
     */
    public function detMoney(){
        $data = [];
        $list = Db::name('order')->where(['status'=>1])->field('created_at,total_price,status')->select();
        $where = date('Y-m-d')." 00:00:00";
        $data['total_price'] = 0;
        $data['longOrderNum'] = 0;
        $data['today'] = 0;
        $data['todayOrderNum'] = 0;
        foreach ($list as $v){
            if($v['status'] == 1){
                $data['longOrderNum']++;
                $data['total_price']  += $v['total_price'];
                if($v['created_at'] > $where){
                    $data['todayOrderNum']++;
                    $data['today'] +=  $v['total_price'];
                }
            }
        }

        $data['usCouNum'] = Db::name('user')->where(['is_delete'=>1,'status'=>1])->count();
        $where = [];
        $where['status'] = 1;
        $where['is_delete'] = 1;
        $where['add_time'] = ['gt',strtotime(date('Y-m-d').' 00:00:00')];
        $data['usCouToNum'] = Db::name('user')->where($where)->count();
        return $data;
    }

    /**
     * 首页饼图
     */
    public function getper($type = 0 ){
        $data = $this->usermodel->roledata();
        if($type ==1){
            return $data;
        }else{
            echo json_encode($data);die;
        }
    }

    /**
     * 首页折线图
     */
    public function getzhexian($type = 0){
        $data = $this->usermodel->moneyWeek();
        if($type == 1){
            return $data;
        }else{
            echo json_encode($data);die;
        }
    }

    /**
     * 修改密码
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        if (intval($this->request->request('id')) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form('SystemUser', 'user/pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致，请重新输入！');
        }
        $user = Db::name('SystemUser')->where('id', session('user.id'))->find();
        if (md5($data['oldpassword']) !== $user['password']) {
            $this->error('旧密码验证失败，请重新输入！');
        }
        if (DataService::save('SystemUser', ['id' => session('user.id'), 'password' => md5($data['password'])])) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 修改资料
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        if (intval($this->request->request('id')) === intval(session('user.id'))) {
            return $this->_form('SystemUser', 'user/form');
        }
        $this->error('只能修改当前用户的资料！');
    }

    /**
     * 导出excel
     */
    public function getExcel(){

        //获取会员角色比列
        $user = self::getper(1);
        $count = 0;

        for($i=0;$i<count($user);$i++){
            $count += $user[$i]['num'];//一共多少会员
        }

        //最近7日
        $seven = self::getzhexian(1);
        //累计交易金额
        $money = self::detMoney();
        //资金提现
        $withdrawa = self::withdrawa();
        //溢出金额
        $overflow = self::overflow();
        //累计满额用户
        $usercapital = self::usercapital();

        //导入相关文件
        require_once APP_PATH."common/PHPExcel/PHPExcel/PHPExcel.php";
        //实例化
        $phpexcel = new \PHPExcel();

        //表格样式设计
        $phpexcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中显示
        $phpexcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $phpexcel->getActiveSheet()->getDefaultColumnDimension('A:J')->setWidth(30);//设置宽度
        $phpexcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);//设置高度
        $phpexcel -> getActiveSheet() -> getColumnDimension(\PHPExcel_Cell::stringFromColumnIndex(0)) -> setAutoSize(true);//自适应

        $phpexcel->getActiveSheet()->mergeCells('B1:F1');//合并单元格 家福宝运营日报
        $phpexcel->getActiveSheet()->mergeCells('C2:C5');//合并单元格 累计注册用户
        $phpexcel->getActiveSheet()->mergeCells('C6:E6');//合并单元格 交易资金
        $phpexcel->getActiveSheet()->mergeCells('B12:F12');//合并单元格 资金提现
        $phpexcel->getActiveSheet()->mergeCells('B15:F15');//合并单元格 溢出资金
        $phpexcel->getActiveSheet()->mergeCells('B18:F18');//合并单元格 满额用户

        //设置比标题
        $phpexcel->getActiveSheet()->setTitle('家富宝运营记录');
        //设置表头
        $phpexcel->getActiveSheet() ->setCellValue('C2','累计注册用户：（'.$count.'）')
            ->setCellValue('B1','家福宝运营日报('.date('Y-m-d').')')
            ->setCellValue('D2','钻石会员:')
            ->setCellValue('D3','金牌会员:')
            ->setCellValue('D4','银牌会员:')
            ->setCellValue('D5','其他会员:')
            ->setCellValue('C6','交易资金')
            ->setCellValue('C7','累计交易金额（元）')
            ->setCellValue('E7','累计交易量（笔）')
            ->setCellValue('C10','今日交易金额（元）')
            ->setCellValue('E10','今日交易量（笔）')
            ->setCellValue('C11','新顾客')
            ->setCellValue('E11','老顾客')
            ->setCellValue('B12','资金提现')
            ->setCellValue('C13','累计提现金额（元）')
            ->setCellValue('E13','累计提现量（笔）')
            ->setCellValue('C14','今日提现金额（元）')
            ->setCellValue('E14','今日提现量（笔）')
            ->setCellValue('B15','溢出金额')
            ->setCellValue('C16','累计溢出金额（元)')
            ->setCellValue('E16','累计溢出量（笔)')
            ->setCellValue('C17','今日溢出金额（元)')
            ->setCellValue('E17','今日溢出量（笔)')
            ->setCellValue('B18','满额用户')
            ->setCellValue('C19','累计满额用户量')
            ->setCellValue('E19','今日满额用户量')

            ->setCellValue('B8',$seven['time'][0])
            ->setCellValue('C8',$seven['time'][1])
            ->setCellValue('D8',$seven['time'][2])
            ->setCellValue('E8',$seven['time'][3])
            ->setCellValue('F8',$seven['time'][4])
            ->setCellValue('G8',$seven['time'][5])
            ->setCellValue('H8',$seven['time'][6]);
        //用foreach从第二行开始写数据，因为第一行是表头
        $i=2;
        foreach($user as $k=>$val){
            $phpexcel->getActiveSheet() ->setCellValue('E'.$i,$val['num']);
            $i++;
        }
        $phpexcel->getActiveSheet() ->setCellValue('D7',$money['total_price']);
        $phpexcel->getActiveSheet() ->setCellValue('F7',$money['longOrderNum']);
        $phpexcel->getActiveSheet() ->setCellValue('D10',$money['today']);
        $phpexcel->getActiveSheet() ->setCellValue('F10',$money['todayOrderNum']);
        $phpexcel->getActiveSheet() ->setCellValue('D11',$money['usCouToNum']);
        $phpexcel->getActiveSheet() ->setCellValue('F11',$money['usCouNum']);
        $phpexcel->getActiveSheet() ->setCellValue('D13',$withdrawa['money']);
        $phpexcel->getActiveSheet() ->setCellValue('F13',$withdrawa['count']);
        $phpexcel->getActiveSheet() ->setCellValue('D14',$withdrawa['newMoney']);
        $phpexcel->getActiveSheet() ->setCellValue('F14',$withdrawa['newnum']);
        $phpexcel->getActiveSheet() ->setCellValue('D16',$overflow['money']);
        $phpexcel->getActiveSheet() ->setCellValue('F16',$overflow['num']);
        $phpexcel->getActiveSheet() ->setCellValue('D17',$overflow['moneytoday']);
        $phpexcel->getActiveSheet() ->setCellValue('F17',$overflow['todaynum']);
        $phpexcel->getActiveSheet() ->setCellValue('D19',$usercapital['maxPay']);
        $phpexcel->getActiveSheet() ->setCellValue('F19',$usercapital['todayMaxPay']);

        $phpexcel->getActiveSheet() ->setCellValue('B9',$seven['data'][0]);
        $phpexcel->getActiveSheet() ->setCellValue('C9',$seven['data'][1]);
        $phpexcel->getActiveSheet() ->setCellValue('D9',$seven['data'][2]);
        $phpexcel->getActiveSheet() ->setCellValue('E9',$seven['data'][3]);
        $phpexcel->getActiveSheet() ->setCellValue('F9',$seven['data'][4]);
        $phpexcel->getActiveSheet() ->setCellValue('G9',$seven['data'][5]);
        $phpexcel->getActiveSheet() ->setCellValue('H9',$seven['data'][6]);

        $obj_Writer = \PHPExcel_IOFactory::createWriter($phpexcel,'Excel5');
        $filename ='家富宝运营记录'. date('Y-m-d').".xls";//文件名
//设置header
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $obj_Writer->save('php://output');//输出
        die();//种植执行
    }

    public function getUserType(){
        $this->table = 'user';
        Db::name($this->table)->where(['status'=>1,'is_delete'=>1])->select();


    }
}
